package com.self.liu.xp.zk;

import org.I0Itec.zkclient.ZkClient;

public class ZkManager {

    private static ZkClient zk = null;

    private static String zkips = "192.168.59.128:2181,192.168.59.129:2181,192.168.59.130:2181";

    private static String path = "/thrift/baseservice";

    private ZkManager() {
    }

    private static void init() {
        if (null == zk) {
            zk = new ZkClient(zkips);
        }
    }

    public static boolean reg(String url) {
        return reg(url, 1);
    }

    public static boolean isReged(String url) {
        init();
        String node = path + "/" + url;
        return zk.exists(node);
    }

    public static boolean reg(String url, int weight) {
        init();
        String node = path + "/" + url;
        if (!zk.exists(node)) {
            if (!zk.exists(path)) {
                zk.createPersistent(path, true);
            }
            zk.createPersistent(node, weight);
            return true;
        } else {
            zk.writeData(node, weight);
            return true;
        }
    }

    public static boolean unReg(String url) {
        init();
        String node = path + "/" + url;
        if (zk.exists(node)) {
            boolean flag = zk.delete(node);
            return flag;
        }
        return false;
    }

    public static void close() {
        zk.close();
    }
}
